package com.heyige.controller;

import javax.validation.Valid;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.heyige.common.CommResponse;
import com.heyige.dto.AdminDto;
import com.heyige.dto.UserDto;
import com.heyige.entity.Admin;
import com.heyige.facade.UserFacade;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@RequestMapping("api/admin")
@RequiredArgsConstructor
@Tag(name = "管理员管理", description = "管理员相关接口")
public class AdminController {

    private final UserFacade userFacade;

    @PostMapping("login")
    @Operation(summary = "管理员登录", description = "管理员通过用户名和密码登录系统")
    public CommResponse<AdminDto.LoginResponse> login(
            @Parameter(description = "登录请求参数") @Valid @RequestBody UserDto.LoginRequest loginRequest) {
        AdminDto.LoginResponse response = userFacade.adminLogin(loginRequest);
        return CommResponse.ok(response);
    }

    @PostMapping("register")
    @Operation(summary = "管理员注册", description = "管理员注册")
    public CommResponse<Admin> register(@Parameter(description = "注册请求参数") @Valid @RequestBody UserDto.RegisterRequest registerRequest) {
        Admin admin = userFacade.adminRegister(registerRequest);
        return CommResponse.ok(admin);
    }

    @PostMapping("logout")
    @Operation(summary = "管理员退出登录", description = "管理员退出登录系统")
    public CommResponse<Void> logout(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
        }
        if (token == null || token.isEmpty()) {
            token = request.getHeader("accessToken");
        }
        userFacade.logoutAdmin(token);
        return CommResponse.ok();
    }

    @GetMapping("info")
    @Operation(summary = "获取管理员信息", description = "获取当前登录管理员的信息")
    public CommResponse<Admin> info(HttpServletRequest request) {
        // 从请求属性中获取管理员ID
        Long adminId = (Long) request.getAttribute("userId");
        Admin admin = userFacade.getAdminInfo(adminId);
        return CommResponse.ok(admin);
    }
    
}